<template>
  <div class="doc-content-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 文档内容 -->
    <article v-else-if="currentLesson" class="doc-article">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="doc-breadcrumb">
        <el-breadcrumb-item :to="{ path: '/docs' }">文档中心</el-breadcrumb-item>
        <el-breadcrumb-item 
          v-for="category in categoryPath" 
          :key="category.id"
          :to="`/docs/category/${category.slug}`"
        >
          {{ category.name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentLesson.title }}</el-breadcrumb-item>
      </el-breadcrumb>
      
      <!-- 文档头部 -->
      <header class="doc-header">
        <h1 class="doc-title">{{ currentLesson.title }}</h1>
        
        <!-- 文档元信息 -->
        <div class="doc-meta">
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            {{ formatDate(currentLesson.updatedAt) }}
          </span>
          <span class="meta-item">
            <el-icon><View /></el-icon>
            {{ currentLesson.viewCount }} 次浏览
          </span>
          <span v-if="currentLesson.difficulty" class="meta-item">
            <el-tag :type="difficultyType">{{ difficultyText }}</el-tag>
          </span>
          <span v-if="currentLesson.duration" class="meta-item">
            <el-icon><Timer /></el-icon>
            约 {{ currentLesson.duration }} 分钟
          </span>
        </div>
        
        <!-- 文档来源 -->
        <div v-if="currentLesson.source" class="doc-source">
          <el-alert :closable="false" type="info">
            <template #title>
              <span>本文档来源于：</span>
              <a :href="currentLesson.source.url" target="_blank" rel="noopener">
                {{ currentLesson.source.name }}
              </a>
              <span v-if="currentLesson.source.version">
                （版本：{{ currentLesson.source.version }}）
              </span>
            </template>
          </el-alert>
        </div>
      </header>
      
      <!-- 文档正文 -->
      <div class="doc-body">
        <!-- 标签 -->
        <div v-if="currentLesson.tags?.length" class="doc-tags">
          <el-tag 
            v-for="tag in currentLesson.tags" 
            :key="tag.id"
            class="tag-item"
            :color="tag.color"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        
        <!-- Markdown 内容 -->
        <div 
          class="markdown-body" 
          v-html="renderedContent"
        />
        
        <!-- 相关文档 -->
        <div v-if="relatedDocs.length" class="related-docs">
          <h3>相关文档</h3>
          <div class="related-list">
            <router-link
              v-for="doc in relatedDocs"
              :key="doc.id"
              :to="`/docs/lesson/${doc.slug || doc.id}`"
              class="related-item"
            >
              <h4>{{ doc.title }}</h4>
              <p>{{ doc.excerpt }}</p>
            </router-link>
          </div>
        </div>
      </div>
      
      <!-- 底部操作 -->
      <footer class="doc-footer">
        <div class="doc-actions">
          <el-button
            v-if="prevDoc"
            @click="navigateToDoc(prevDoc)"
          >
            <el-icon><ArrowLeft /></el-icon>
            上一篇：{{ prevDoc.title }}
          </el-button>
          
          <el-button
            v-if="nextDoc"
            type="primary"
            @click="navigateToDoc(nextDoc)"
          >
            下一篇：{{ nextDoc.title }}
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        
        <!-- 同步信息 -->
        <div v-if="currentLesson.lastSyncAt" class="sync-info">
          <span>最后同步时间：{{ formatDate(currentLesson.lastSyncAt) }}</span>
          <el-button 
            v-if="currentLesson.needsUpdate"
            type="warning"
            size="small"
            @click="handleSync"
          >
            <el-icon><Refresh /></el-icon>
            更新文档
          </el-button>
        </div>
      </footer>
    </article>
    
    <!-- 空状态 -->
    <el-empty v-else description="文档不存在或已删除" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  Clock, View, Timer, ArrowLeft, ArrowRight, Refresh 
} from '@element-plus/icons-vue'
import { useDocsStore } from '@/stores/docs'
import type { DocLesson } from '@/types/docs'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const docsStore = useDocsStore()

// 状态
const loading = ref(false)
const relatedDocs = ref<DocLesson[]>([])
const prevDoc = ref<DocLesson | null>(null)
const nextDoc = ref<DocLesson | null>(null)

// 获取当前课程
const currentLesson = computed(() => docsStore.currentLesson)

// 计算属性
const difficultyType = computed(() => {
  const map = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return map[currentLesson.value?.difficulty || 'intermediate'] || ''
})

const difficultyText = computed(() => {
  const map = {
    beginner: '入门',
    intermediate: '进阶',
    advanced: '高级'
  }
  return map[currentLesson.value?.difficulty || 'intermediate'] || ''
})

const categoryPath = computed(() => {
  if (!currentLesson.value) return []
  return docsStore.getCategoryPath(currentLesson.value.categoryId)
})

const renderedContent = computed(() => {
  if (!currentLesson.value?.content) return ''
  
  // 暂时返回预格式化的文本，等待安装 marked 库后再渲染 Markdown
  // TODO: 安装 marked 和 highlight.js 库后启用 Markdown 渲染
  return `<pre>${currentLesson.value.content.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>`
})

// 方法
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const loadDoc = async () => {
  const docId = route.params.id as string
  if (!docId) return
  
  loading.value = true
  try {
    await docsStore.fetchDocLesson(docId)
    await loadRelatedDocs()
    loadNavDocs()
  } finally {
    loading.value = false
  }
}

const loadRelatedDocs = async () => {
  if (!currentLesson.value) return
  
  // 获取同分类的其他文档
  const categoryDocs = docsStore.lessonsByCategory.get(currentLesson.value.categoryId) || []
  relatedDocs.value = categoryDocs
    .filter(doc => doc.id !== currentLesson.value!.id)
    .slice(0, 3)
}

const loadNavDocs = () => {
  if (!currentLesson.value) return
  
  const categoryDocs = docsStore.lessonsByCategory.get(currentLesson.value.categoryId) || []
  const currentIndex = categoryDocs.findIndex(doc => doc.id === currentLesson.value!.id)
  
  prevDoc.value = currentIndex > 0 ? categoryDocs[currentIndex - 1] : null
  nextDoc.value = currentIndex < categoryDocs.length - 1 ? categoryDocs[currentIndex + 1] : null
}

const navigateToDoc = (doc: DocLesson) => {
  router.push(`/docs/lesson/${doc.slug || doc.id}`)
}

const handleSync = async () => {
  if (!currentLesson.value?.source) return
  
  try {
    await docsStore.syncDocSource(currentLesson.value.source.name)
    ElMessage.success('文档同步任务已启动')
  } catch (error) {
    ElMessage.error('启动同步任务失败')
  }
}

// 监听路由变化
watch(() => route.params.id, () => {
  loadDoc()
})

// 初始化
onMounted(() => {
  loadDoc()
})
</script>

<style lang="scss" scoped>
.doc-content-page {
  max-width: 900px;
  margin: 0 auto;
}

.loading-container {
  padding: 2rem;
}

.doc-article {
  background-color: var(--el-bg-color);
  border-radius: 0.5rem;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.doc-breadcrumb {
  margin-bottom: 2rem;
}

.doc-header {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--el-border-color);
}

.doc-title {
  font-size: 2rem;
  font-weight: 700;
  margin: 0 0 1rem 0;
  line-height: 1.3;
}

.doc-meta {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  color: var(--el-text-color-secondary);
  font-size: 0.875rem;
  
  .meta-item {
    display: flex;
    align-items: center;
    gap: 0.25rem;
  }
}

.doc-source {
  margin-top: 1rem;
  
  a {
    color: var(--el-color-primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.doc-body {
  margin-bottom: 3rem;
}

.doc-tags {
  margin-bottom: 1.5rem;
  
  .tag-item {
    margin-right: 0.5rem;
  }
}

// Markdown 样式
.markdown-body {
  font-size: 1rem;
  line-height: 1.75;
  color: var(--el-text-color-primary);
  
  h1, h2, h3, h4, h5, h6 {
    margin-top: 2rem;
    margin-bottom: 1rem;
    font-weight: 600;
    line-height: 1.3;
  }
  
  h1 { font-size: 1.875rem; }
  h2 { font-size: 1.5rem; }
  h3 { font-size: 1.25rem; }
  h4 { font-size: 1.125rem; }
  
  p {
    margin-bottom: 1rem;
  }
  
  a {
    color: var(--el-color-primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  code {
    background-color: var(--el-fill-color);
    padding: 0.125rem 0.375rem;
    border-radius: 0.25rem;
    font-size: 0.875em;
  }
  
  pre {
    background-color: var(--el-fill-color);
    border-radius: 0.5rem;
    padding: 1rem;
    overflow-x: auto;
    margin-bottom: 1rem;
    
    code {
      background-color: transparent;
      padding: 0;
      font-size: 0.875rem;
    }
  }
  
  ul, ol {
    margin-bottom: 1rem;
    padding-left: 2rem;
  }
  
  li {
    margin-bottom: 0.5rem;
  }
  
  blockquote {
    border-left: 4px solid var(--el-color-primary);
    padding-left: 1rem;
    margin: 1rem 0;
    color: var(--el-text-color-secondary);
  }
  
  table {
    width: 100%;
    margin-bottom: 1rem;
    border-collapse: collapse;
    
    th, td {
      padding: 0.75rem;
      border: 1px solid var(--el-border-color);
    }
    
    th {
      background-color: var(--el-fill-color);
      font-weight: 600;
    }
  }
  
  img {
    max-width: 100%;
    height: auto;
    border-radius: 0.5rem;
    margin: 1rem 0;
  }
}

.related-docs {
  margin-top: 3rem;
  padding-top: 2rem;
  border-top: 1px solid var(--el-border-color);
  
  h3 {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 1rem;
  }
}

.related-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
}

.related-item {
  display: block;
  padding: 1rem;
  border: 1px solid var(--el-border-color);
  border-radius: 0.5rem;
  text-decoration: none;
  transition: all 0.2s;
  
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  h4 {
    font-size: 1rem;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 0.5rem;
  }
  
  p {
    font-size: 0.875rem;
    color: var(--el-text-color-secondary);
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.doc-footer {
  margin-top: 3rem;
  padding-top: 2rem;
  border-top: 1px solid var(--el-border-color);
}

.doc-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.sync-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.875rem;
  color: var(--el-text-color-secondary);
}

// 响应式
@media (max-width: 768px) {
  .doc-article {
    padding: 1.5rem;
  }
  
  .doc-title {
    font-size: 1.5rem;
  }
  
  .doc-meta {
    flex-wrap: wrap;
    gap: 1rem;
  }
  
  .doc-actions {
    flex-direction: column;
    gap: 1rem;
    
    .el-button {
      width: 100%;
    }
  }
}
</style> 